import os, cv2, json, math, statistics
from glob import glob
import numpy as np

img_dir_path = "/home/smartgis/workspace/data/风电/预巡/label"
json_path_list = glob(img_dir_path+"/*.json")


def get_len(point1,point2):
    len_size = math.sqrt((point1[0]-point2[0])**2+((point1[1]-point2[1])**2))
    return len_size

def angle_between_lines(line_1, line_2):
    p1, p2 = line_1
    p3, p4 = line_2
    # 计算线段1的方向向量
    dx1 = p2[0] - p1[0]
    dy1 = p2[1] - p1[1]

    # 计算线段2的方向向量
    dx2 = p4[0] - p3[0]
    dy2 = p4[1] - p3[1]

    # 计算向量的点积
    dot_product = dx1 * dx2 + dy1 * dy2

    # 计算向量的模长
    norm1 = np.sqrt(dx1**2 + dy1**2)
    norm2 = np.sqrt(dx2**2 + dy2**2)

    # 计算夹角的余弦值
    cos_theta = dot_product / (norm1 * norm2)

    # 防止浮点数精度问题
    cos_theta = np.clip(cos_theta, -1.0, 1.0)

    # 计算夹角（弧度）
    angle_radians = np.arccos(cos_theta)

    # 转换为度数
    angle_degrees = np.degrees(angle_radians)

    return angle_degrees


for json_path in json_path_list:
    head = []
    apexs = []
    with open(json_path,"r") as f:
        label_json = json.load(f)
    img_path = img_dir_path+"/"+label_json["imagePath"].replace("\\","/")
    img_data = cv2.imread(img_path)
    cv2.imwrite("temp.jpg",cv2.resize(img_data,[800,600]))
    for shape in label_json["shapes"]:
        if shape["label"] == "风帽" :
            head = shape["points"][0]
        elif shape["label"] == "塔筒顶点" :
            head_back = shape["points"][0]
        elif "叶尖" in shape["label"]:
            apexs.append(shape["points"][0])
    if len(head)>0:
        have_head = True
    else:
        have_head = False
        head = head_back
    line_1 = [head,apexs[0]]
    line_2 = [head,apexs[1]]
    line_3 = [head,apexs[2]]
    angle_1 = angle_between_lines(line_1,line_2)
    angle_2 = angle_between_lines(line_2,line_3)
    angle_3 = angle_between_lines(line_3,line_1)

    variance = statistics.stdev([angle_1,angle_2,angle_3])
    print("{:.2f}, {:.2f}, {:.2f}, {:.2f} | {}".format(variance, angle_1,angle_2,angle_3, have_head))

